<?php

namespace liketp;

use Closure;

/**
 * Web 应用管理类
 * 负责处理 http 请求
 */

class Http
{
    protected $app;

    public function __construct(App $app)
    {
        $this->app = $app;
    }

    public function run()
    {
        $this->app->initialize();
        $request = $this->app->make('request');
        return $this->dispatch($request);
    }

    public function dispatch($request)
    {
        return $this->app->middleware->pipeline('global')
            ->send($request)
            ->then(function () use ($request) {
                return $this->dispatchToRoute($request);
            });
    }

    public function dispatchToRoute($request)
    {
        $withRoute = function () {
            $routeDir = $this->app->getRoutePath();
            $files = glob($routeDir . '*.php');
            foreach ($files as $file) {
                include($file);
            }
        };
        return $this->app->route->dispatch($request, $withRoute);
    }

    public function end()
    {
        $this->app->end(true);
    }
}
